import json

import cv2
from django.core import serializers
from django.http import StreamingHttpResponse, HttpResponse, JsonResponse

from model.object_detect.object_detection import object_detection, global_intrusion_record, set_active_objects
from recognition.models import IntrusionData
from user.models import User


def object_recognition(request, uid):
    def frame_generator():
        for frame, cnt in object_detection():
            if cnt is not None:
                record = global_intrusion_record[-1]
                IntrusionData.objects.create(uid=User.objects.filter(id=int(uid))[0], count=record.get('number'),
                                             intrusion_time=record.get('time'),
                                             path=record.get('path'))
            ret, jpeg = cv2.imencode('.jpg', frame)
            frame_data = jpeg.tobytes()

            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame_data + b'\r\n\r\n')
    return StreamingHttpResponse(frame_generator(), content_type='multipart/x-mixed-replace; boundary=frame')

def intrusion_record(request, uid):
    record = IntrusionData.objects.filter(uid=int(uid))
    json_data = serializers.serialize('json', record)
    return HttpResponse(json_data, content_type='application/json')

def intrusion_image(request):
    image_url = request.GET.get("image_url")
    image = cv2.imread(image_url)
    ret, jpg = cv2.imencode('.jpg', image)
    frame_data = jpg.tobytes()
    return HttpResponse(frame_data, content_type='image/jpeg')

def add_objects(request):
    body = json.loads(request.body)
    # print(body.get('data'))
    set_active_objects(body.get('data'))
    data = {
        "code": 200,
        "message": "success",
        "data": None
    }
    return HttpResponse(json.dumps(data))


